<?php
	require("tokenizer.php");
	
//this is the layout only. Pseudocode will be posted.
class Member
{
	/*Member Fucntions*/
	
public static function getLoginInfo($id){
		return array($username, $password);
	}
	
	function getContent(){
		return array($articles, $images);
	}
	
public static function getLinks($fileName){
			$text = file2string($fileName);	
			$text = convert2utf($text);
			$urls = extract_html_urls($text);
			
			$a = $urls['a']['href'];
	return $a;
}

public static function getLinkGraph($urls,$filename){
		foreach($urls as $link){
				$file = "articles/".$link;
				$res = mysql_query("SELECT CID FROM articles_table WHERE Filename = '$file'")or die("Could not get articles ID".mysql_error());
				$row = mysql_fetch_row($res);
				$CID[] = $row[0];
			}
			
		if(!empty($row)){
			$linkstr= implode("-", $CID);
			mysql_query("UPDATE articles_table SET links = '$linkstr' WHERE Filename = '$filename'")or die("Links could not be loaded. ".mysql_error());
		}
		 $res = mysql_query("SELECT CID, links FROM articles_table")or die("Query Failed".mysql_error());
		 
		 while($row = mysql_fetch_row($res)){
			$arr = explode("-", $row[1]);
			$contID = $row[0];
			$linkGraph[$contID] = $arr;	 
		 }
		return $linkGraph;
	}
	
public static function calculatePageRank($linkGraph, $dampingFactor = 0.15) {
        $pageRank = array();
        $tempRank = array();
        $nodeCount = count($linkGraph); 

        // initialise the PR as 1/n
        foreach($linkGraph as $node => $outbound) {
                $pageRank[$node] = 1/$nodeCount;
                $tempRank[$node] = 0;
        }

        $change = 1;
        $i = 0;
        while($change > 0.00005 && $i < 100) {
                $change = 0;
                $i++;

                // distribute the PR of each page
                foreach($linkGraph as $node => $outbound) {
                        $outboundCount = count($outbound);
                        foreach($outbound as $link) { 
                                $tempRank[$link] += $pageRank[$node] / $outboundCount;
                        }
                }
                
                $total = 0;
                // calculate the new PR using the damping factor
                foreach($linkGraph as $node => $outbound) {
                        $tempRank[$node]  = ($dampingFactor / $nodeCount)
                                                + (1-$dampingFactor) * $tempRank[$node];
                        $change += abs($pageRank[$node] - $tempRank[$node]);
                        $pageRank[$node] = $tempRank[$node];
                        $tempRank[$node] = 0;
                        $total += $pageRank[$node];
                }

                // Normalise the page ranks so it's all a proportion 0-1
                foreach($pageRank as $node => $score) {
                        $pageRank[$node] /= $total;
                }
        }
        
        return $pageRank;
	}
	
public static function uploadFile($fileName,$filetype, $title, $userID, $private, $kw1, $kw2=NULL, $kw3=NULL){
		if($filetype == "art"){
			$text = file2string($fileName);
			$text = convert2utf($text);
			$urls = extract_html_urls($text);
			$text = strip_html_tags($text);
			$text = strip_punctuation($text);
			$text = strip_numbers($text);
			$words = stemText($text);
			$lastModified = date('Y-m-d');
			
			$a = $urls['a']['href'];
			
			$res = mysql_query("SELECT Stopword FROM stopword_table WHERE Stopword like '%$title%' OR Stopword like '%$kw1%'")
						or die("Stopword could not be retrieved. ".mysql_error());
			$arr = mysql_fetch_array($res);
			if(!empty($arr)){
				return -1;	//stopword found
			}
			elseif(check_stopwords($words))
				return -1;	//stopword found
			else{				
				$keywordCount = countWords($words);
				unset($words);
				$keywords = getKeywords($keywordCount,1);
				
				$ins_article = "INSERT INTO articles_table(Filename,Title,UID, KW1, KW2, KW3, KW4, KW5, KW6, KW7, KW8, KW9, KW10, KW11, KW12, KW13, KW14, KW15, KW16, KW17, KW18, KW19, KW20, private, lastmodified)
								VALUES('$fileName','$title', $userID, '$kw1', '$kw2', '$kw3', '$keywords[0]', '$keywords[1]', '$keywords[2]', '$keywords[3]', '$keywords[4]', '$keywords[5]', '$keywords[6]',
								'$keywords[7]', '$keywords[8]', '$keywords[9]', '$keywords[10]', '$keywords[11]', '$keywords[12]', '$keywords[13]','$keywords[14]',
								'$keywords[15]', '$keywords[16]', '$private', '$lastModified')";
				mysql_query($ins_article)or die('Insert article failed. '.mysql_error());
				$res = mysql_query("SELECT CID FROM articles_table WHERE Filename='$fileName'")or die('Query Failed. '.mysql_error());
				$res = mysql_fetch_row($res);
				$CID = $res[0];
				$keywords[17]=$kw1; $keywords[18]=$kw2; $keywords[19]=$kw3;
				
				for($i = 0; $i<=16; $i++){
					mysql_query("INSERT INTO general_keywords(Keyword, ContentType, CID, UID) VALUES('$keywords[$i]', '$filetype', $CID, $userID)") or die('Query Failed. '.mysql_error());
					}
				
				//get pagerank
				$linkGraph = Member::getLinkGraph($a,$fileName);
				$pageRank = Member::calculatePageRank($linkGraph);
				
				foreach($pageRank as $key =>$rank){
					$pr = floatval($rank);
					$k = intval($key);
					mysql_query("UPDATE articles_table SET pagerank = $pr WHERE CID = $k")or die("PageRank could not be updated. ".mysql_error());
				
				}
			}
		}
		elseif($filetype == "img"){
			mysql_query("INSERT INTO images_table(Filename, Title, UID, KW1, private) VALUES('$fileName', '$title', $userID, '$kw1', '$private')") or die('Query Failed. '.mysql_error());
			
			$res = mysql_query("SELECT CID FROM articles_table WHERE Filename='$fileName'")or die('Query 2 Failed. '.mysql_error());
			$res = mysql_fetch_row($res);
			$CID = intval($res[0]);
			mysql_query("INSERT INTO general_keywords(Keyword, ContentType, CID, UID) VALUES('$kw1', '$filetype', $CID, $userID)") or die('Insert KW Failed. '.mysql_error());
		}
		else
			return -2;//invalid file type
		@mysql_connect(close);
	}
public static function updateFile($oldFileName, $newFileName, $filetype){	
		if($filetype = 'art'){
			$text = file2string($newFileName);
			$text = convert2utf($text);
			$urls = extract_html_urls($text);
			$text = strip_html_tags($text);
			$text = strip_punctuation($text);
			$text = strip_numbers($text);
			$words = stemText($text);
			$lastModified = date('Y-m-d');
			
			$a = $urls['a']['href'];
			
			if(check_stopwords($words))
				return -1;	
			else{
				$keywordCount = countWords($words);
				unset($words);
				$keywords = getKeywords($keywordCount,1);
				
				mysql_query("UPDATE articles_table SET Filename = '$newFileName', KW4 ='$keywords[0]', KW5 ='$keywords[1]', KW6 ='$keywords[2]', KW7 ='$keywords[3]',
						KW8 ='$keywords[4]', KW9 ='$keywords[5]', KW10 ='$keywords[6]', KW11 ='$keywords[7]', KW12 ='$keywords[8]', KW13 ='$keywords[9]',
						KW14 ='$keywords[10]', KW15 ='$keywords[11]', KW16 ='$keywords[12]', KW17 ='$keywords[13]', KW18 ='$keywords[14]', KW19 ='$keywords[15]',
						KW20 ='$keywords[16]', lastmodified = '$lastModified' WHERE Filename = '$oldFileName'" )or die('File update failed. '.mysql_error());
						
				}
				
				//get pagerank
				$linkGraph = Member::getLinkGraph($a,$newFileName);
				$pageRank = Member::calculatePageRank($linkGraph);
				
				foreach($pageRank as $key =>$rank){
					$pr = floatval($rank);
					$k = intval($key);
					mysql_query("UPDATE articles_table SET pagerank = $pr WHERE CID = $k")or die("PageRank could not be updated. ".mysql_error());
				
				}
				/*$res = mysql_query("SELECT CID FROM articles_table WHERE Filename = $oldFileName");
				$res = mysql_fetch_row($res);
				$CID = $res[0];*/
				
				/*updating GKwT still needed*/
		}			
		elseif($filetype == "img"){
			mysql_query("UPDATE images_table SET Filename = '$newFilename' WHERE Filename = $oldFileName")or die('Image update failed. '.mysql_error());
		}
		else
			return -2;
		}
public static function deleteFile($fileName, $fileType){
		if ($fileType == "art"){
			mysql_query("DELETE FROM articles_table WHERE Filename='$fileName'")or die("Article file could not be deleted. ".mysql_error());
			return 1;
			}
		elseif ($fileType == "img"){
			mysql_query("DELETE FROM images_table WHERE Filename='$fileName'")or die("Image file could not be deleted. ".mysql_error());
			return 2;
		}
		else
			return -1;
	}

public static function getUserProfileInfo($id){
		$result = mysql_query("SELECT * FROM user_table WHERE UID=$id");
		
		if ($result)
		{
			// retreive as an associative array
			$row = mysql_fetch_array($result);	
			
			$firstName = $row['FName'];
			$lastName = $row['LName'];
			$credits = $row['Credits'];	// Need entry for credits
			$username = $row['Username'];
			$password = $row['Password'];
			$gender = $row['Gender'];
			$DOB = $row['DOB'];
			$email = $row['Email'];
			$ID = $id;
			$status = $row['Status'];		// Need entry for membership status
			$articles = array();
			$images = array();
			
			// get a list of content IDs (articles)
			$getArticles = mysql_query("SELECT CID, Filename, Title,lastmodified, pageviews, private FROM articles_table WHERE UID=$id");
			//$articles = mysql_fetch_array($getArticles);

			// get a list of content IDs (images)			
			$getImages = mysql_query("SELECT CID, Filename, Title, pageviews, private FROM images_table WHERE UID=$id");
			//$images = mysql_fetch_array($getImages);
			
			return $userInfo = array($firstName, $lastName, $credits, $username, $password, $gender, $DOB, $email, $status, $getArticles, $getImages);
			
		}
		
		//from database get variables 
		//Name = fName + lName
		//email
		//DOB
		//Gender
		//points
		//rank
		//getcontent
	}
	
	/*Attributes*/
	protected $ID;
	protected $firstName;
	protected $lastName;
	protected $credits;
	protected $username;
	protected $password;
	protected $gender;
	protected $DOB;
	protected $email;
	protected $status;	// new entry added for approving/denying new members

	// each variable will store a list of IDs which correspond to the member's articles
	public static $articles;
	public static $images;
}	
?>